package messenger;

import java.awt.Color;
import java.awt.Font;
import java.io.*;
import javax.swing.JFrame;
import javazoom.jl.player.Player;
import javax.swing.JTextArea;

public class ChatWindow {    
    private BufferedReader entrada;
    private PrintWriter saida;
    private String localIp;
    private String hostIp;
    private JFrame frame;
    private JTextArea incoming;    
    
    public ChatWindow(BufferedReader entrada,PrintWriter saida, String localIp, String hostIp) {
        this.entrada = entrada;
        this.saida = saida;
        this.localIp = localIp;
        this.hostIp = hostIp; 
        
        ChatWindowBuilder chatBuilder = new ChatWindowBuilder("Messenger Maroto", entrada, saida, localIp, hostIp);
        chatBuilder.CreateAll();
        frame = chatBuilder.getFrame();
        frame.setVisible(true);
        incoming = chatBuilder.getIncoming();
        Thread readerThread = new Thread(new IncomingReader());
        readerThread.start();        
    }  
    
    public class IncomingReader implements Runnable{

        public void run() {
            String mensagem;
            try{                
                while( (mensagem = entrada.readLine()) != null ){                    
                    if(!frame.isShowing()){ // se o usuário fechar a janela, ao se enviar
                       frame.show();     //uma mensagem abriremos a frame denovo.                        
                       frame.setExtendedState( JFrame.ICONIFIED ); // evitar que a janela a ser aberta sobreponha as outras.
                           
                       try{// também tocara uma musiquinha.
                            File file = new File("sons\\type.mp3");
                            InputStream in = (InputStream) (new  FileInputStream(file));
                            Player plr = new Player(in);
                            plr.play();                                           
                        }catch(Exception e){e.printStackTrace();}
                    } 
                    System.out.println("ler " + mensagem);
                    String[] str = hostIp.split("/");                 
                   
                    incoming.append(str[1]+" (your friend):   " + mensagem + "\n"); 

                }
            }catch(Exception e){e.printStackTrace();}            
        }    
    } 
}